"""
Display and logic for the Army Builder screen
"""
import pygame, sys, time
from pygame.locals import *

WHITE = (255,255,255)
BLACK = (0,0,0)
GRAY = (200,200,200)

#render text spanning multiple lines
def renderMultiText(text, font, width):
    words = text.split(" ")
    line = ""
    surfaces = []
    for w in words:
        if font.size(line+w+" ")[0] > width:
            surfaces.append(font.render(line, True, BLACK))
            line = w + " "
        else:
            line = line + w + " "
    surfaces.append(font.render(line, True, BLACK))
    return surfaces

def buildArmy(windowSurface, assets):
    images = assets["images"]
    units = assets["units"]
    
    rects = []
    army = []
    points = 0

    FIELDWIDTH = 800
    
    basicFont = pygame.font.SysFont(None, 16)
    midFont = pygame.font.SysFont(None, 32)
    bigFont = pygame.font.SysFont(None, 48)
    
    for i in range(len(images)):
        rects.append(images[i].get_rect())
        rects[i].left = (i*60)%600 + 50
        rects[i].top =  (i//10)*60 + 50
    
    run = True
    unitHovered = False
    hoveredIndex = -1
    
    #make the buttons and rects
    save = midFont.render("Save P1 ", True, BLACK, GRAY)
    saveRect = save.get_rect()
    saveRect.left = 0
    saveRect.top = 500
    
    save2 = midFont.render("Save P2 ", True, BLACK, GRAY)
    save2Rect = save.get_rect()
    save2Rect.left = 100
    save2Rect.top = 500
    
    reset = midFont.render("Reset ", True, BLACK, GRAY)
    resetRect = reset.get_rect()
    resetRect.left = 200
    resetRect.top = 500
    
    exit = midFont.render("Exit ", True, BLACK, GRAY)
    exitRect = exit.get_rect()
    exitRect.left = 300
    exitRect.top = 500
        
    while run:
        event = pygame.event.wait()
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if event.key == K_F1:
                pygame.image.save(windowSurface, "screenshot"+str(time.time())+".png")
        if event.type == MOUSEBUTTONDOWN:
            for i in range(len(rects)):
                if rects[i].collidepoint(event.pos):
                    if points + units[i].points <= 900:
                        army.append(units[i].name)
                        points = points + units[i].points
            if saveRect.collidepoint(event.pos):
                file = open("armies/p1army.dat", "w")
                file.write(" ".join(army))
                file.close()
                army = []
                points = 0
            if save2Rect.collidepoint(event.pos):
                file = open("armies/p2army.dat", "w")
                file.write(" ".join(army))
                file.close()
                points = 0
                army = []
            if resetRect.collidepoint(event.pos):
                army = []
                points = 0
            if exitRect.collidepoint(event.pos):
                run = False
        if event.type == MOUSEMOTION:
            found = False
            for i in range(len(rects)):
                if rects[i].collidepoint(event.pos):
                    found = True
                    unitHovered = True
                    hoveredIndex = i 
                    break
            if not found:
                unitHovered = False
                hoveredIndex = -1
        windowSurface.fill((255,255,255))
        pygame.draw.rect(windowSurface, GRAY, pygame.Rect(800,0,200,600))
        
        for i in range(len(images)):
            windowSurface.blit(images[i], rects[i])
        
        if unitHovered:
            unitName = midFont.render(units[hoveredIndex].name, True, BLACK)
            unitHP = midFont.render("HP: " + str(units[hoveredIndex].hp), True, BLACK)
            unitMove = midFont.render("Move: " + str(units[hoveredIndex].move), True, BLACK)
            unitRange = midFont.render("Range: " + str(units[hoveredIndex].range), True, BLACK)
            unitAttack = midFont.render("Attack: " + str(units[hoveredIndex].attack), True, BLACK)
            unitDefense = midFont.render("Defense: " + str(units[hoveredIndex].defense), True, BLACK)
        
            windowSurface.blit(images[hoveredIndex], (FIELDWIDTH+75, 100))
            windowSurface.blit(unitName, (FIELDWIDTH, 150))
            windowSurface.blit(unitHP, (FIELDWIDTH, 175))
            windowSurface.blit(unitMove, (FIELDWIDTH, 200))
            windowSurface.blit(unitRange, (FIELDWIDTH, 225))
            windowSurface.blit(unitAttack, (FIELDWIDTH, 250))
            windowSurface.blit(unitDefense, (FIELDWIDTH, 275))
        
            if units[hoveredIndex].skill != None:
                skillName = midFont.render(units[hoveredIndex].skill.name, True, BLACK)
                skillDescription = renderMultiText(units[hoveredIndex].skill.description, basicFont, 200)
                windowSurface.blit(skillName, (FIELDWIDTH, 325))
                
                for i in range(len(skillDescription)):
                    windowSurface.blit(skillDescription[i], (FIELDWIDTH, 350 + (i*15)))
        
        armyNames = midFont.render(" ".join(army), True, BLACK)
        curr = midFont.render("Current Army Cost: "+str(points), True, BLACK)
        windowSurface.blit(armyNames, (0,560))
        windowSurface.blit(curr, (0,535))
        windowSurface.blit(save, saveRect)
        windowSurface.blit(save2, save2Rect)
        windowSurface.blit(reset, resetRect)
        windowSurface.blit(exit, exitRect)
        
        pygame.display.update()     